<template>
  <a-modal
    :title="title"
    width="90%"
    centered
    :visible="visible"
    :confirmLoading="loading"
    @ok="_submit"
    @cancel="_cancel"
  >
    <a-spin :spinning="loading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="30">
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="配资合同编号">
              <a-input
                class="contractNo"
                placeholder="请输入配资合同编号"
                v-decorator="[
                  'netsignContractNo',
                  { rules: [{ required: true, message: '请输入配资合同编号', whitespace: true }] },
                ]"
                @change="_getContractDtl"
              />
              <span class="handleBtns">
                <span>{{ netSignStatusMap[netSignInfo.status] }}</span
                >&ensp; <a @click="_syncNetSignStatus">同步</a>&ensp;
                <a target="_blank" :href="netSignInfo.previewUrl" v-if="netSignInfo.previewUrl">查看</a>&ensp;
              </span>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="商户">
              <a-select
                placeholder="请选择商户"
                v-decorator="['merchantId', { rules: [{ required: true, message: '请选择商户，商户不能为空！' }] }]"
              >
                <a-select-option :value="item.merchantId" v-for="item in merchantSelList" :key="item.merchantId">
                  {{ item.merchantName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="配资服务商">
              <a-select
                placeholder="请选择配资服务商"
                v-decorator="[
                  'capitalId',
                  { rules: [{ required: true, message: '请选择配资服务商，配资服务商不能为空！' }] },
                ]"
              >
                <a-select-option :value="item.capitalId" v-for="item in capitalSelList" :key="item.capitalId">{{
                  item.capitalName
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="30">
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="配资金额">
              <a-input
                placeholder="请输入配资金额"
                v-decorator="[
                  'loanAmount',
                  { rules: [{ required: true, message: '请输入配资金额', whitespace: true }] },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="月回款金额">
              <a-input
                placeholder="请输入月回款金额"
                v-decorator="[
                  'monthRepaymentAmount',
                  { rules: [{ required: true, message: '请输入月回款金额', whitespace: true }] },
                ]"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="服务费金额">
              <a-input
                placeholder="请输入服务费金额"
                v-decorator="[
                  'serviceFeeAmount',
                  { rules: [{ required: true, message: '请输入服务费金额', whitespace: true }] },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="30">
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="还款日(每月几号)">
              <a-select
                placeholder="请选择还款日"
                v-decorator="[
                  'repaymentDay',
                  { rules: [{ required: true, message: '请选择还款日，还款日不能为空！' }] },
                ]"
              >
                <a-select-option
                  :value="item + 1"
                  v-for="item in Array.from(Array(31), (_val, index) => index)"
                  :key="item.capitalId"
                >{{ item + 1 }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="服务费支付状态">
              <a-select
                placeholder="请选择服务费支付状态"
                v-decorator="[
                  'serviceFeePayStatus',
                  { rules: [{ required: true, message: '请选择服务费支付状态，服务费支付状态不能为空！' }] },
                ]"
              >
                <a-select-option :value="0">未支付</a-select-option>
                <a-select-option :value="1">已支付</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="8" :sm="24">
            <a-form-item label="商户回款状态">
              <a-select
                placeholder="请选择商户回款状态"
                v-decorator="[
                  'isUnfreeze',
                  { rules: [{ required: true, message: '请选择商户回款状态，商户回款状态不能为空！' }] },
                ]"
              >
                <a-select-option :value="0">冻结</a-select-option>
                <a-select-option :value="1">解冻</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item label="图片">
              <a-upload
                list-type="picture-card"
                :file-list="fileList"
                :customRequest="customRequest"
                :remove="delFile"
                @preview="handlePreview"
                v-decorator="['pics', { rules: [{ required: true, message: '图片不能为空!' }] }]"
              >
                <div v-if="fileList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">Upload</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-divider></a-divider>
      <a-descriptions :column="{ xxl: 4, xl: 6, lg: 6, md: 6, sm: 3, xs: 1 }">
        <template #title><a>已选合同</a></template>
        <a-descriptions-item label="已选订单">{{ selContractData.contractNums }}个</a-descriptions-item>
        <a-descriptions-item label="已选金额">{{ selContractData.contractAmount }}元</a-descriptions-item>
        <a-descriptions-item label="已到回款">{{ selContractData.repaymentAmount }}元</a-descriptions-item>
        <a-descriptions-item label="标记金额">{{ selContractData.markPayAmount }}元</a-descriptions-item>
        <a-descriptions-item label="未到金额">{{ selContractData.lastAmount }}元</a-descriptions-item>
        <a-descriptions-item label="待分金额">{{ selContractData.allocateAmount }}元</a-descriptions-item>
      </a-descriptions>
      <a-divider></a-divider>
      <a-descriptions>
        <template #title><a>合同选择</a></template>
        <a-descriptions-item>
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="6" :sm="24">
                  <a-form-item label="商户">
                    <a-input v-model="queryParam.merchantKeyword" placeholder="" />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <s-table
            ref="table"
            size="default"
            rowKey="contractNo"
            :columns="columns"
            :data="loadData"
            :alert="false"
            :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
            showPagination="auto"
            listName="dataList"
          >
            <span slot="serial" slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <div slot="userInfo" slot-scope="text, record">
              <div>
                <span>{{ record.userName }}</span
                >&nbsp;&nbsp;<span>{{ record.userMobile }}</span>
              </div>
              <div>{{ record.userNetsignAccount }}</div>
            </div>
            <div slot="amountInfo" slot-scope="text, record">
              <div>
                <span>{{ record.depositAmount }}</span
                >/<span>{{ record.contractAmount }}</span>
              </div>
              <div>
                <span>已还{{ record.repaymentNums }}期</span>/<span>共{{ record.repaymentCycle }}期</span>
              </div>
            </div>
            <span slot="serviceFeeAmount" slot-scope="text, record">
              <span>{{
                text ? `${text}/${((record.serviceFeeAmount * 100) / record.contractAmount).toFixed(2)}` : '—'
              }}</span>
            </span>
            <span slot="repaymentDay" slot-scope="text">
              <span>{{ text | repaymentDayFilter }}</span>
            </span>
            <span slot="serviceFeePayStatus" slot-scope="text">
              <span>{{ text | serviceFeePayStatusFilter }}</span>
            </span>
            <span slot="repaymentStatus" slot-scope="text">
              <span>{{ text | repaymentStatusFilter }}</span>
            </span>
            <span slot="capitalContractStatus" slot-scope="text">
              <span>{{ text | capitalContractStatusFilter }}</span>
            </span>
          </s-table>
        </a-descriptions-item>
      </a-descriptions>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { uploadFile, getNetSignInfo, getMerchantSelList, getCapitalSelList } from '@/api/common'
import { STable, Ellipsis } from '@/components'
import { getContractList, syncNetSignStatus } from '@/api/custContractManage'
import { throttle } from '@/utils/util'

// 表单字段
const fields = [
  'netsignContractNo',
  'merchantId',
  'capitalId',
  'loanAmount',
  'monthRepaymentAmount',
  'serviceFeeAmount',
  'repaymentDay',
  'serviceFeePayStatus',
  'isUnfreeze',
  'pics'
]

const netSignStatusMap = {
  0: '等待签约',
  1: '签约中',
  2: '已签约',
  3: '过期',
  4: '拒签',
  6: '作废',
  '-2': '状态异常'
}

const statusMap = {
  1: {
    status: 'processing',
    text: '启用'
  },
  2: {
    status: 'default',
    text: '冻结'
  }
}

const serviceFeePayStatusMap = {
  0: {
    text: '未支付'
  },
  1: {
    text: '已支付'
  }
}

const repaymentStatusMap = {
  1: {
    text: '正常'
  },
  2: {
    text: '逾期'
  },
  3: {
    text: '结清'
  }
}

const capitalContractStatusMap = {
  0: {
    text: '未打包'
  },
  1: {
    text: '已打包'
  },
  2: {
    text: '已结清'
  },
  4: {
    text: '已冻结'
  }
}

const repaymentDayMap = {
  1: {
    text: '次月今日'
  },
  2: {
    text: '次月5日'
  },
  3: {
    text: '次月15日'
  },
  4: {
    text: '次月25日'
  },
  5: {
    text: '一周后'
  },
  6: {
    text: '本月月底'
  }
}

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
    align: 'center',
    fixed: 'left',
    width: 80
  },
  {
    title: '合同编号',
    dataIndex: 'contractNo',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '签约人信息',
    scopedSlots: { customRender: 'userInfo' },
    align: 'center'
  },
  {
    title: '签约时间',
    dataIndex: 'netsignCompleteTime',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '定金/金额',
    dataIndex: 'amountInfo',
    scopedSlots: { customRender: 'amountInfo' },
    align: 'center'
  },
  {
    title: '还款状态',
    dataIndex: 'repaymentStatus',
    scopedSlots: { customRender: 'repaymentStatus' },
    align: 'center'
  }
]

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  components: {
    STable,
    Ellipsis
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    title: {
      type: String,
      default: ''
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.columns = columns
    this.netSignStatusMap = netSignStatusMap
    return {
      form: this.$form.createForm(this),
      queryParam: {},
      netSignInfo: {},
      previewVisible: false,
      previewImage: '',
      fileList: [],
      merchantSelList: [],
      capitalSelList: [],
      selContractData: {
        contractNums: 0,
        contractAmount: 0,
        repaymentAmount: 0,
        markPayAmount: 0,
        lastAmount: 0,
        allocateAmount: 0
      },
      selectedRowKeys: [],
      selectedRows: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getContractList(requestParameters)
          .then((res) => {
            return res.result
          })
          .catch((e) => {})
      }
    }
  },
  methods: {
    /**
     * 获取合同状态
     */
    _getContractDtl () {
      this.$nextTick(() => {
        if (!this.form.getFieldValue('netsignContractNo')) return
        throttle(() => {
          getNetSignInfo({
            contractNo: this.form.getFieldValue('netsignContractNo')
          })
            .then((res) => {
              this.netSignInfo = res.result
            })
            .catch((e) => {})
        }, 2000)
      })
    },
    /**
     * 同步签约状态
     */
    _syncNetSignStatus (record) {
      if (!this.form.getFieldValue('netsignContractNo')) {
        this.$message.warn('请输入合同编号')
        return false
      }
      syncNetSignStatus({ contractNo: this.form.getFieldValue('netsignContractNo') })
        .then(() => {
          this.$message.info('同步成功')
        })
        .catch(() => {})
    },
    /**
     * 提交表单
     */
    _submit: function () {
      const contractList = this.selectedRowKeys.map((item) => {
        return {
          contractNo: item
        }
      })
      this.$emit('ok', { contractList })
    },
    /**
     * 取消
     */
    _cancel: function () {
      this.$emit('cancel')
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },

    customRequest (options) {
      const params = new FormData()
      this.uploadLoading = true
      params.append('file', options.file)
      params.append('uploadType', 'merchant')
      uploadFile(params)
        .then((res) => {
          this.fileList.push({
            uid: this.fileList.length - 1,
            name: options.file.name,
            status: 'done',
            url: res.url
          })
          this.form.setFieldsValue({
            pics: this.fileList.map((item) => item.url).join(',')
          })
        })
        .catch((e) => {})
    },
    /**
     * 删除图片
     */
    delFile (options) {
      const curIndex = this.fileList.findIndex((item) => {
        return item.name === options.name
      })
      this.fileList.splice(curIndex, 1)
      this.form.setFieldsValue({
        pics: this.fileList.map((item) => item.url).join(',')
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.selContractData = {
        contractNums: 0,
        contractAmount: 0,
        repaymentAmount: 0,
        markPayAmount: 0,
        lastAmount: 0,
        allocateAmount: 0
      }
      this.selContractData.contractNums = this.selectedRowKeys.length
      this.selectedRows.forEach((item, index) => {
        this.selContractData.allocateAmount += item.allocateAmount
        this.selContractData.contractAmount += item.contractAmount
        this.selContractData.repaymentAmount += item.repaymentAmount
        this.selContractData.markPayAmount += item.markPayAmount
        this.selContractData.lastAmount += item.contractAmount - item.repaymentAmount
        this.selContractData.allocateAmount += item.allocateAmount
      })
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
    serviceFeePayStatusFilter (type) {
      return serviceFeePayStatusMap[type].text
    },
    repaymentStatusFilter (type) {
      return repaymentStatusMap[type].text
    },
    capitalContractStatusFilter (type) {
      return capitalContractStatusMap[type].text
    },
    repaymentDayFilter (type) {
      return repaymentDayMap[type].text
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))
    this.$watch('visible', () => {
      this.netSignInfo = {}
      this.selContractData = {
        contractNums: 0,
        contractAmount: 0,
        repaymentAmount: 0,
        markPayAmount: 0,
        lastAmount: 0,
        allocateAmount: 0
      }
      this.selectedRowKeys = []
      this.selectedRows = []
      this.fileList = []
    })
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
    getMerchantSelList({})
      .then((res) => {
        this.merchantSelList = res.dataList
      })
      .catch((e) => {})
    getCapitalSelList()
      .then((res) => {
        this.capitalSelList = res.dataList
      })
      .catch((e) => {})
  },
  mounted () {}
}
</script>
<style lang="less" scope>
.tableTitle {
  padding: 0 0 20px;
}
.contractNo {
  display: inline;
  width: 200px;
}
.handleBtns {
  padding: 0 20px;
}
</style>
